/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the oil4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.telecom.oil.smart.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.telecom.oil.common.core.exception.BusinessException;
import com.telecom.oil.smart.api.dto.SetRecordMarketReq;
import com.telecom.oil.smart.api.dto.SetRecordReq;
import com.telecom.oil.smart.api.dto.SetRecordWithMarketReq;
import com.telecom.oil.smart.api.entity.OilUser;
import com.telecom.oil.smart.api.entity.SetRecord;
import com.telecom.oil.smart.api.entity.SetRecordMarket;
import com.telecom.oil.smart.api.entity.SetRegion;
import com.telecom.oil.smart.api.util.PageUtils;
import com.telecom.oil.smart.api.vo.SetRecordExcelVo;
import com.telecom.oil.smart.api.vo.SetRecordMapVo;
import com.telecom.oil.smart.api.vo.SetRecordVo;
import com.telecom.oil.smart.mapper.SetRecordMapper;
import com.telecom.oil.smart.service.OilUserService;
import com.telecom.oil.smart.service.SetRecordMarketService;
import com.telecom.oil.smart.service.SetRecordService;
import com.telecom.oil.smart.service.SetRegionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 套餐信息调查表
 *
 * @author jianghuai
 * @date 2023-02-07 11:55:00
 */
@Service
public class SetRecordServiceImpl extends ServiceImpl<SetRecordMapper, SetRecord> implements SetRecordService {

	@Autowired
	private OilUserService oilUserService;

	@Autowired
	private SetRecordMarketService setRecordMarketService;

	@Autowired
	private SetRegionService setRegionService;

	@Autowired
	private SetRecordMapper setRecordMapper;

	/**
	 * PC端-分页查询
	 * @param page
	 * @param query
	 * @return
	 */
	@Override
	public IPage pageQuery(Page page, QueryWrapper<SetRecord> query) {
		Page<SetRecord> pageData = this.page(page, query);
		List<SetRecordVo> vos = pageData.getRecords().stream().map(item -> {
			SetRecordVo vo = new SetRecordVo();
			BeanUtils.copyProperties(item, vo);
			//填充用户名
			OilUser oilUser = oilUserService.findById(item.getUserId());
			vo.setUserName(oilUser.getUserName() != null ? oilUser.getUserName() : null);
			//填充行政区名称
			SetRegion level2Region = setRegionService.findById(item.getLevel2Code());
			vo.setLevel2Name(level2Region != null ? level2Region.getName() : null);
			SetRegion level3Region = setRegionService.getById(item.getLevel3Code());
			vo.setLevel3Name(level3Region != null ? level3Region.getName() : null);
			vo.setPermanentDetail(item.getPermanent() == 1? "是" : "否");
			return vo;
		}).collect(Collectors.toList());
		Page<SetRecordVo> returnPage = new Page<>();
		returnPage.setRecords(vos);
		returnPage.setTotal(pageData.getTotal());
		return returnPage;
	}

	/**
	 * 微信小程序端-分页查询
	 * @param req
	 * @return
	 */
	@Override
	public PageUtils getSetRecordPage(SetRecordReq req) {
		LambdaQueryWrapper<SetRecord> lambdaQuery = Wrappers.lambdaQuery();
		lambdaQuery.like(StringUtils.isNotEmpty(req.getPhone()), SetRecord::getPhone, req.getPhone());
		lambdaQuery.like(StringUtils.isNotEmpty(req.getHouseHolder()), SetRecord::getHouseHolder, req.getHouseHolder());
		lambdaQuery.orderByDesc(SetRecord::getCreateTime);
		Page<SetRecord> page = this.page(new Page<>(req.getCurrent(), req.getSize()), lambdaQuery);
		List<SetRecordVo> voList = page.getRecords().stream().map(item -> {
			SetRecordVo vo = new SetRecordVo();
			BeanUtils.copyProperties(item, vo);

			//填充用户名
			OilUser oilUser = oilUserService.findById(item.getUserId());
			vo.setUserName(oilUser.getUserName() != null ? oilUser.getUserName() : null);
			//填充行政区名称
			SetRegion level2Region = setRegionService.findById(item.getLevel2Code());
			vo.setLevel2Name(level2Region != null? level2Region.getName() : null);
			SetRegion level3Region = setRegionService.getById(item.getLevel3Code());
			vo.setLevel3Name(level3Region != null? level3Region.getName() : null);
			return vo;
		}).sorted(new Comparator<SetRecordVo>() {
			@Override
			public int compare(SetRecordVo o1, SetRecordVo o2) {
				return -(o1.getCreateTime().compareTo(o2.getCreateTime()));
			}
		}).collect(Collectors.toList());
		return new PageUtils(voList, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
	}

	/**
	 * 微信小程序端-查询套餐详情
	 * @param id
	 * @return
	 */
	@Override
	public SetRecordVo getSetRecordById(Long id) {
		return setRecordMapper.selectSetRecordDetailById(id);
	}

	/**
	 * 微信小程序端-根据乡镇/街道、村/社区、组别、门牌号查询最近一条记录
	 * @param level2Code
	 * @param level3Code
	 * @param houseGroup
	 * @param houseNumber
	 * @return
	 */
	@Override
	public SetRecordVo getSetRecordByCondition(Integer level2Code, Integer level3Code, Integer houseGroup, Integer houseNumber) {
		LambdaQueryWrapper<SetRecord> query = Wrappers.lambdaQuery();
		query.eq(SetRecord::getLevel2Code, level2Code);
		query.eq(SetRecord::getLevel3Code, level3Code);
		query.eq(SetRecord::getHouseGroup, houseGroup);
		query.eq(SetRecord::getHouseNumber, houseNumber);
		query.orderByDesc(SetRecord::getCreateTime);
		List<SetRecord> recordList = this.list(query);
		if(recordList != null && recordList.size() > 0){
			SetRecordVo vo = new SetRecordVo();
			SetRecord record = recordList.get(0);
			BeanUtils.copyProperties(record, vo);
			//填充行政区名称
			SetRegion level2Region = setRegionService.findById(record.getLevel2Code());
			vo.setLevel2Name(level2Region != null? level2Region.getName() : null);
			SetRegion level3Region = setRegionService.getById(record.getLevel3Code());
			vo.setLevel3Name(level3Region != null? level3Region.getName() : null);
			return vo;
		}
		return null;
	}

	/**
	 * 微信小程序端-我的套餐记录
	 * @param req
	 * @return
	 */
	@Override
	public PageUtils findMySetRecord(SetRecordReq req) {
		LambdaQueryWrapper<SetRecord> lambdaQuery = Wrappers.lambdaQuery();
		lambdaQuery.like(StringUtils.isNotEmpty(req.getHouseHolder()), SetRecord::getHouseHolder, req.getHouseHolder());
		lambdaQuery.eq(SetRecord::getUserId, req.getUserId());
		lambdaQuery.orderByDesc(SetRecord::getCreateTime);
		Page<SetRecord> page = this.page(new Page<>(req.getCurrent(), req.getSize()), lambdaQuery);
		OilUser oilUser = oilUserService.getById(req.getUserId());
		List<SetRecordVo> voList = page.getRecords().stream().map(item -> {
			SetRecordVo vo = new SetRecordVo();
			BeanUtils.copyProperties(item, vo);
			vo.setUserName(oilUser.getUserName() != null ? oilUser.getUserName() : null);
			//填充行政区名称
			SetRegion level2Region = setRegionService.findById(item.getLevel2Code());
			vo.setLevel2Name(level2Region != null? level2Region.getName() : null);
			SetRegion level3Region = setRegionService.getById(item.getLevel3Code());
			vo.setLevel3Name(level3Region != null? level3Region.getName() : null);
			return vo;
		}).sorted(new Comparator<SetRecordVo>() {
			@Override
			public int compare(SetRecordVo o1, SetRecordVo o2) {
				return -(o1.getCreateTime().compareTo(o2.getCreateTime()));
			}
		}).collect(Collectors.toList());
		return new PageUtils(voList, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
	}

	/**
	 * 微信小程序端-地图展示套餐分布情况
	 * @return
	 */
	@Override
	public List<SetRecordMapVo> listAllSetRecord() {
		return setRecordMapper.listSetRecordMap().stream().map(item -> {
			return SetRecordMapVo.builder()
					.id(item.getId())
					.houseHolder(item.getHouseHolder())
					.longitude(item.getLongitude())
					.latitude(item.getLatitude())
					.op(item.getOp())
					.build();
		}).collect(Collectors.toList());
	}

	/**
	 * 微信小程序端-新增或修改套餐
	 * @param setRecord
	 * @param user
	 */
	@Override
	@Transactional
	public void uploadSetRecord(SetRecordWithMarketReq req, com.telecom.oil.common.security.service.OilUser user) {
		if (Objects.isNull(req.getId())) {
			//新增套餐
			SetRecord setRecord = new SetRecord();
			BeanUtils.copyProperties(req, setRecord);
			setRecord.setCreateBy(user.getUsername());
			setRecord.setUserId(user.getId());
			setRecord.setUpdateBy("");
			this.save(setRecord);
		}else {
			//修改套餐
			SetRecord setRecord = new SetRecord();
			BeanUtils.copyProperties(req, setRecord);
			setRecord.setUpdateBy(user.getUsername());
			setRecord.setUserId(user.getId());
			this.updateById(setRecord);
		}
		//营销成功时添加营销记录
		if(Objects.nonNull(req.getMarket()) && StringUtils.isNotBlank(req.getMarket().getBusinessType())){
			SetRecordMarketReq recordMarket = req.getMarket();
			SetRecordMarket setRecordMarket = new SetRecordMarket();
			BeanUtils.copyProperties(req.getMarket(), setRecordMarket);
			setRecordMarket.setUserId(user.getId());
			setRecordMarket.setCreateBy(user.getUsername());
			setRecordMarket.setUpdateBy("");
			setRecordMarketService.save(setRecordMarket);
		}

	}

	/**
	 * 微信小程序端-通过id修改套餐
	 * @param setRecord
	 * @return
	 */
	@Override
	public boolean updateSetRecordById(SetRecord setRecord) {
		if(setRecord == null){
			return false;
		}
		SetRecord ctRecord = this.getById(setRecord.getId());
		if(ctRecord == null){
			throw new BusinessException("未查到此条记录");
		}
		ctRecord.setLevel2Code(setRecord.getLevel2Code());
		ctRecord.setLevel3Code(setRecord.getLevel3Code());
		ctRecord.setHouseGroup(setRecord.getHouseGroup());
		ctRecord.setHouseNumber(setRecord.getHouseNumber());
		ctRecord.setHouseHolder(setRecord.getHouseHolder());
		ctRecord.setPermanent(setRecord.getPermanent());
		ctRecord.setPhone(setRecord.getPhone());
		ctRecord.setOp(setRecord.getOp());
		ctRecord.setHouseCConsume(setRecord.getHouseCConsume());
		ctRecord.setCurrentSet(setRecord.getCurrentSet());
		ctRecord.setMenuExpireTime(setRecord.getMenuExpireTime());
		ctRecord.setVisitDetails(setRecord.getVisitDetails());
		ctRecord.setSiteImage(setRecord.getSiteImage());
		ctRecord.setAddress(setRecord.getAddress());
		ctRecord.setRemark(setRecord.getRemark());
		ctRecord.setLatitude(setRecord.getLatitude());
		ctRecord.setLongitude(setRecord.getLongitude());
		return this.updateById(ctRecord);
	}

	@Override
	public List<SetRecordExcelVo> listRecord() {
		List<SetRecord> recordList = this.list(Wrappers.emptyWrapper());
		// 转换成execl 对象输出
		return recordList.stream().map(record -> {
			SetRecordExcelVo recordExcelVo = new SetRecordExcelVo();
			BeanUtil.copyProperties(record, recordExcelVo);
			//填充用户名
			OilUser oilUser = oilUserService.findById(record.getUserId());
			recordExcelVo.setUserName(oilUser != null? oilUser.getUserName() : "");
			//填充行政区名称
			SetRegion level2Region = setRegionService.findById(record.getLevel2Code());
			recordExcelVo.setLevel2Name(level2Region != null? level2Region.getName() : "");
			SetRegion level3Region = setRegionService.getById(record.getLevel3Code());
			recordExcelVo.setLevel3Name(level3Region != null? level3Region.getName() : "");

			recordExcelVo.setPermanentDetail(record.getPermanent() == 1? "是" : "否");
			return recordExcelVo;
		}).collect(Collectors.toList());
	}

}
